﻿using CleanLite.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace CleanLite.Web.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled || context.HttpContext.Response.HasStarted)
            {
                return;
            }
            ApiResponse errorResponse;
            int statusCode = 500; // 默认服务器内部错误
            switch (context.Exception)
            {
                case ArgumentNullException argNullEx:
                    statusCode = (int)HttpStatusCode.BadRequest; // 400 Bad Request
                    errorResponse = ApiResponse.FailResponse($"请求参数错误: {argNullEx.Message}");
                    break;

                case ArgumentException argEx:
                    statusCode = (int)HttpStatusCode.BadRequest; // 400 Bad Request
                    errorResponse = ApiResponse.FailResponse($"请求参数无效: {argEx.Message}");
                    break;

                case UnauthorizedAccessException unauthorizedEx:
                    statusCode = (int)HttpStatusCode.Unauthorized; // 401 Unauthorized
                    errorResponse = ApiResponse.FailResponse($"未经授权的访问: {unauthorizedEx.Message}");
                    break;

                case System.ComponentModel.DataAnnotations.ValidationException validationEx:
                    statusCode = (int)HttpStatusCode.BadRequest; // 400 Bad Request
                    errorResponse = ApiResponse.FailResponse($"数据验证失败: {validationEx.Message}");
                    break;

                default:
                    // 对于其他未处理的异常，返回通用服务器内部错误
                    errorResponse = ApiResponse.FailResponse($"服务器内部错误: {context.Exception.Message}");
                    break;
            }

            context.HttpContext.Response.StatusCode = statusCode;
            context.Result = new JsonResult(errorResponse);

            // 标记异常已处理，避免ASP.NET Core继续处理
            context.ExceptionHandled = true;
        }
    }
}